import React, { useEffect } from 'react';
import Vditor from 'vditor';
import 'vditor/src/assets/scss/index.scss';
import styles from './index.less';

//@ts-ignore
const initOutline = () => {
  const headingElements: Element[] = [];
  const preview = document.getElementById('preview');
  if (!preview) {
    return;
  }
  Array.from(preview.children).forEach((item) => {
    if (
      item.tagName.length === 2 &&
      item.tagName !== 'HR' &&
      item.tagName.indexOf('H') === 0
    ) {
      headingElements.push(item);
    }
  });

  let toc: { id: string; offsetTop: number }[] = [];
  return window.addEventListener('scroll', () => {
    const scrollTop = window.scrollY;
    toc = [];
    headingElements.forEach((item) => {
      toc.push({
        id: item.id,
        // @ts-ignore
        offsetTop: item.offsetTop,
      });
    });

    const currentElement = document.querySelector(
      '.vditor-outline__item--current',
    );
    for (let i = 0, iMax = toc.length; i < iMax; i++) {
      if (scrollTop < toc[i].offsetTop - 30) {
        if (currentElement) {
          currentElement.classList.remove('vditor-outline__item--current');
        }
        let index = i > 0 ? i - 1 : 0;
        const spIndex = document.querySelector(
          'span[data-target-id="' + toc[index].id + '"]',
        );
        if (spIndex) {
          spIndex.classList.add('vditor-outline__item--current');
        }
        break;
      }
    }
  });
};

export type VditorPreviewType = {
  markdown: string;
};

const VditorPreview: React.FC<VditorPreviewType> = ({ markdown }) => {
  //html渲染后初始化md
  useEffect(() => {
    const preview = document.getElementById('preview');
    let srollEvent: any;
    if (preview) {
      // @ts-ignore
      Vditor.preview(preview, markdown, {
        mode: 'dark',
        outline: true,
        hljs: {
          enable: true,
          style: 'native',
          lineNumber: true,
        },
        speech: {
          enable: true,
        },
        anchor: 1,
        renderers: {
          renderHeading: (node, entering) => {
            const id = Lute.GetHeadingID(node);
            if (entering) {
              return [
                `<h${node.__internal_object__.HeadingLevel} id='${id}' class='heading'><span class='heading__prefix'></span><span class='heading__content'>`,
                Lute.WalkContinue,
              ];
            } else {
              return [
                `</span><span class='heading__suffix'></span><a id='vditorAnchor-${id}' class='vditor-anchor' href='#${id}'><svg viewBox='0 0 16 16' version='1.1' width='16' height='16'><path fill-rule='evenodd' d='M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z'></path></svg></a></h${node.__internal_object__.HeadingLevel}>`,
                Lute.WalkContinue,
              ];
            }
          },
        },
        after() {
          if (window.innerWidth <= 768) {
            return;
          }
          const outlineElement = document.getElementById('outline');
          // @ts-ignore
          Vditor.outlineRender(
            document.getElementById('preview'),
            outlineElement,
          );

          if (outlineElement && outlineElement.innerText.trim() !== '') {
            outlineElement.style.display = 'block';
            srollEvent = initOutline();
          }
        },
      });
    }
    return () => {
      if (srollEvent) {
        window.removeEventListener('scroll', srollEvent);
      }
    };
  }, [markdown]);

  return (
    <div className={styles.inlineStyles}>
      <div id={'preview'} />
      <div id={'outline'} />
      <div style={{ display: 'none' }}>{markdown}</div>
    </div>
  );
};

export default VditorPreview;
